import dayjs from "dayjs"
import "dayjs/locale/zh-cn"
import { getTicketModeStore } from "../hox/ticketModeStore"
import { TicketModeEnum } from "@/utils/enum"

export const getSubDesc = (date: string, needDate?: boolean): string => {
  const today = dayjs().format("YYYY-MM-DD")

  const diff = dayjs(date).diff(dayjs(today), "days")

  let label = ""
  const overWeeks = Math.floor((dayjs(today).day() + diff) / 8)

  if (diff === 0) {
    label = "今天 "
  } else if (diff === 1) {
    label = "明天 "
  } else if (diff === 2) {
    label = "后天 "
  } else if (diff > 2 && diff < 14) {
    //.fill("下")
    label = `${new Array(overWeeks).join("")}${dayjs(date)
      .locale("zh-cn")
      .format("dddd")
      .replace("星期", "周")} `
  }
  return `${needDate ? `${label}${dayjs(date).format("MM月DD日")}` : ""}`
}

export const resizeImgUrl = (url: string, size: number = 300) => {
  // https://gw.alicdn.com/ 开头 不区分大小写
  const regex = new RegExp('^https://gw.alicdn.com/', 'i')
  if (regex.test(url)) {
    const pattern = /_\d{2,4}x\d{2,4}/i
    if (pattern.test(url)) return url.replace(pattern, `_${size}x${size}`)
    return `${url}_${size}x${size}.jpg`
  }
  return url
}

type StringifyOptions = {
  encode?: boolean;
  arrayFormat?: 'brackets' | 'indices' | 'repeat';
};
export const qsStringify = (obj: any, options: StringifyOptions = { encode: true, arrayFormat: 'repeat' }) => {
  const pairs: string[] = []

  function encodeValue(value: string): string {
    return options.encode ? encodeURIComponent(value) : value
  }

  function handleArray(key: string, arr: any[]): void {
    const formattedKey = encodeValue(key)
    switch (options.arrayFormat) {
      case 'brackets':
        arr.forEach((val) => {
          pairs.push(`${formattedKey}[]=${encodeValue(String(val))}`)
        })
        break
      case 'indices':
        arr.forEach((val, index) => {
          pairs.push(`${formattedKey}[${index}]=${encodeValue(String(val))}`)
        })
        break
      case 'repeat':
        arr.forEach((val) => {
          pairs.push(`${formattedKey}=${encodeValue(String(val))}`)
        })
        break
      default:
        throw new Error('Invalid arrayFormat option')
    }
  }

  function traverse(obj: any, prefix = ''): void {
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        const value = obj[key]
        const fullKey = prefix ? `${prefix}[${encodeValue(key)}]` : encodeValue(key)
        if (Array.isArray(value)) {
          handleArray(fullKey, value)
        } else if (value instanceof Object && !(value instanceof Date)) {
          traverse(value, fullKey)
        } else {
          pairs.push(`${fullKey}=${encodeValue(String(value))}`)
        }
      }
    }
  }

  traverse(obj)
  return pairs.join('&')
}

export function arrayGroupBy<T, R>(data: T[], callbackfn: (item: T) => R, defaultCallback?: R) {
  let res = new Map<R, T[]>()
  data.forEach(item => {
    let key = callbackfn(item)
    if (key === undefined && defaultCallback) key = defaultCallback
    res.get(key) ? res.get(key)?.push(item) : res.set(key, [item])
  })
  return res
}

/**
 * 
 * @param seat 单个座位
 * @param hasCoupon 是否使用优惠券
 * @description 使用优惠券，售价返回原价，不使用优惠券，售价返回最低价
 */
export function getSeatPrice(seat: Movie.IsvFilmSeatAreaPriceDatum, hasCoupon: boolean) {
  const { officialPrice, fastPrice, specialPrice, sectionId } = seat
  const base = {
    sectionId,
    officialPrice,
  }

  if (hasCoupon) {
    return {
      ...base,
      sellPrice: officialPrice,
      lineThroughPrice: undefined,
    }
  }
  const { ticketModeList } = getTicketModeStore() || {}
  let sellPrice = Math.min(specialPrice, fastPrice)
  if (ticketModeList && ticketModeList.length === 1) {
    if (ticketModeList[0] === TicketModeEnum.FastTicket) sellPrice = fastPrice
    if (ticketModeList[0] === TicketModeEnum.SlowTicket) sellPrice = specialPrice
  }
  return {
    ...base,
    sellPrice,
    lineThroughPrice: officialPrice,
  }
}

export const phoneReg = {
  phone: /^(?:(?:\+|00)86)?1\d{10}$/
}